

#import "TakePhotoController.h"

@interface TakePhotoController ()

@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@end

@implementation TakePhotoController

- (id)init
{
    if (self = [super init]) {
        self.isEdit = NO;
        self.isSaveToAlbum = NO;
    }
    return self;
}

- (UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}

- (void)addIndicatorViewToPickerView:(UIView *)pickerView
{
    self.indicatorView.center = pickerView.center;
    [pickerView addSubview:self.indicatorView];
    [self.indicatorView startAnimating];
}

- (void)removeIndicatorViewFromPikerView:(UIView *)pickerView
{
    [self.indicatorView stopAnimating];
    [self.indicatorView removeFromSuperview];
    self.indicatorView = nil;
}

- (void)startTakePhotoFromViewControl:(UIViewController *)viewControl
{
    UIImagePickerControllerSourceType sourceType;
    switch (self.type) {
        case TakePhotoFromCamera:
            sourceType = UIImagePickerControllerSourceTypeCamera;
            break;
        case TakePhotoFromPhotoLibrary:
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            break;
        case TakePhotoSavedPhotosAlbum:
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            break;
        default:
            sourceType = UIImagePickerControllerSourceTypeCamera;
            break;
    }
    
    if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = self.isEdit;
        picker.sourceType = sourceType;
        [viewControl presentViewController:picker animated:YES completion:nil];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"温馨提示", @"Tip")
                                                            message:NSLocalizedString(@"您的设备不支持该功能", @"Info")
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
        [alertView show];
    }
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [UIApplication sharedApplication].statusBarHidden = NO;
    [self addIndicatorViewToPickerView:picker.view];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        NSData *data;
        NSString *filePath;
        NSString *fileName;
        if ([mediaType isEqualToString:@"public.image"]) {
            UIImage *originImage;
            if (self.isEdit) {
                originImage = [info objectForKey:UIImagePickerControllerEditedImage];
            } else {
                originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
            
            if (self.isSaveToAlbum) {
                UIImageWriteToSavedPhotosAlbum(originImage, NULL, NULL, NULL);
            }
            
            UIImage *scaleImage = [self scaleImage:originImage toScale:0.3];
            data = UIImageJPEGRepresentation(scaleImage, 0.8);

            //这里将图片放在沙盒的documents文件夹中
            NSString * DocumentsPath = DE.mainPath;//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            //文件管理器
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //把刚刚图片转换的data对象拷贝至沙盒中 并保存为random.png
            int randon = (arc4random() % 100000000000) + 1;
            fileName = [NSString stringWithFormat:@"pic_%d_%@_iOS.png",randon,DE.userId];
            [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
            //得到选择后沙盒中图片的完整路径
            filePath = [NSString  stringWithFormat:@"%@%@",DocumentsPath,fileName];
            
            
            [fileManager createFileAtPath:filePath contents:data attributes:nil];
 
            
        }
        UIImage *image = [UIImage imageWithData:data];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.blockComplete) {
                [self removeIndicatorViewFromPikerView:picker.view];
                [picker dismissViewControllerAnimated:YES completion:nil];
                NSDictionary * paraMap = @{@"file":filePath,@"filename":fileName,@"length":@"0"};
                
                self.blockComplete(image,paraMap);
            }
        });
    });
}

-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    CGFloat width = image.size.width*scaleSize;
    CGFloat height = image.size.height*scaleSize;
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [image drawInRect:CGRectMake(0, 0, width, height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


@end
